/**
 * @file can_sdk_example_simple.cpp
 * @brief 六维力传感器CAN SDK简化交互式示例程序
 * @version 1.0.0
 * @date 2025-01-14
 */

#include "six_axis_sensor_can_sdk.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <csignal>
#include <sstream>
#include <iomanip>
#include <cstdlib>

using namespace SixAxisSensorCAN;

// 全局变量
std::atomic<bool> g_running(true);
SixAxisSensorCANSDK* g_sdk = nullptr;

void signalHandler(int signal) {
    std::cout << "\n收到信号 " << signal << "，正在退出..." << std::endl;
    g_running = false;
    if (g_sdk) {
        g_sdk->closeCAN();
    }
    exit(0);
}

/**
 * @brief 数据回调函数
 */
void onDataReceived(const ForceData& data) {
    auto now = std::chrono::system_clock::now();
    auto time_t = std::chrono::system_clock::to_time_t(now);
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
    
    std::cout << std::put_time(std::localtime(&time_t), "%H:%M:%S") 
              << "." << std::setfill('0') << std::setw(3) << ms.count()
              << " " << data.toString() << std::endl;
}

/**
 * @brief 手动选择CAN接口
 */
std::string selectCANInterface(SixAxisSensorCANSDK& sdk) {
    auto interfaces = sdk.scanCANInterfaces();
    
    if (interfaces.empty()) {
        std::cerr << "❌ 未找到CAN接口，请配置接口:" << std::endl;
        std::cerr << "   # 虚拟CAN接口:" << std::endl;
        std::cerr << "   sudo modprobe vcan" << std::endl;
        std::cerr << "   sudo ip link add dev vcan0 type vcan" << std::endl;
        std::cerr << "   sudo ip link set up vcan0" << std::endl;
        std::cerr << "   # 真实CAN接口 (CAN-FD):" << std::endl;
        std::cerr << "   sudo ip link set dev can1 up type can bitrate 1000000 dbitrate 1000000 fd on" << std::endl;
        return "";
    }
    
    std::cout << "\n📡 找到CAN接口:" << std::endl;
    for (size_t i = 0; i < interfaces.size(); ++i) {
        std::cout << "  " << (i + 1) << ". " << interfaces[i] << std::endl;
    }
    
    // 让用户手动选择
    std::cout << "请选择CAN接口 (1-" << interfaces.size() << "): ";
    std::string input;
    int choice = 1; // 默认选择第一个
    
    if (std::getline(std::cin, input) && !input.empty()) {
        try {
            choice = std::stoi(input);
        } catch (...) {
            choice = 1;
        }
    }
    
    // 验证选择范围
    if (choice < 1 || choice > static_cast<int>(interfaces.size())) {
        choice = 1;
    }
    
    std::cout << "🚀 选择CAN接口: " << interfaces[choice - 1] << std::endl;
    return interfaces[choice - 1];
}

/**
 * @brief 交互式设置去皮模式
 */
bool selectTareMode(SixAxisSensorCANSDK& sdk) {
    std::cout << "\n🧹 去皮功能设置:" << std::endl;
    std::cout << "  1. 开启去皮 (清零当前读数)" << std::endl;
    std::cout << "  2. 关闭去皮" << std::endl;
    std::cout << "请选择 [1-2]: ";
    
    std::string input;
    int choice = 2; // 默认关闭去皮
    
    // 检查是否需要退出
    if (!g_running.load()) {
        std::cout << "⏭️ 程序退出中，默认关闭去皮" << std::endl;
        return true;
    }
    
    if (std::getline(std::cin, input)) {
        try {
            choice = std::stoi(input);
        } catch (...) {
            choice = 2;
        }
    }
    
    // 验证选择范围
    if (choice < 1 || choice > 2) {
        choice = 2;
    }
    
    switch (choice) {
        case 1: {
            std::cout << "🧹 正在开启去皮功能..." << std::endl;
            ErrorCode result = sdk.setTareFunction(true);
            if (result == ErrorCode::SUCCESS) {
                std::cout << "✅ 去皮功能已开启，当前读数已清零" << std::endl;
            } else {
                std::cout << "⚠️ 去皮设置可能失败 (错误码: " << static_cast<int>(result) << ")" << std::endl;
                std::cout << "💡 提示: 去皮功能可能需要稳定的力值读数才能执行" << std::endl;
            }
            return true;
        }
        case 2: {
            std::cout << "🧹 正在关闭去皮功能..." << std::endl;
            ErrorCode result = sdk.setTareFunction(false);
            if (result == ErrorCode::SUCCESS) {
                std::cout << "✅ 去皮功能已关闭" << std::endl;
            } else {
                std::cout << "⚠️ 去皮关闭可能失败 (错误码: " << static_cast<int>(result) << ")" << std::endl;
            }
            return true;
        }
        default:
            return true;
    }
}

/**
 * @brief 显示设备信息
 */
void showDeviceInfo(SixAxisSensorCANSDK& sdk) {
    std::cout << "\n📋 读取设备信息..." << std::endl;
    std::cout << "=== 六维力传感器设备信息 ===" << std::endl;
    
    // 先读取版本信息(会触发设备名称读取)
    uint16_t hw_ver, sw_ver;
    ErrorCode result = sdk.getVersion(hw_ver, sw_ver);
    
    // 读取设备名称
    std::string device_name;
    if (sdk.getFullVersionString(device_name) == ErrorCode::SUCCESS && !device_name.empty()) {
        std::cout << "🏷️  设备名称: " << device_name << std::endl;
    }
    
    // 读取详细版本信息
    std::string hw_version_str, sw_version_str;
    if (sdk.getDetailedVersionStrings(hw_version_str, sw_version_str) == ErrorCode::SUCCESS) {
        std::cout << "📝 软件版本: " << sw_version_str << std::endl;
    } else {
        std::cout << "⚠️  版本信息读取失败 (错误码: " << static_cast<int>(result) << ")" << std::endl;
        std::cout << "💡 提示: 请检查CAN通信连接" << std::endl;
    }
    
    // 读取序列号
    std::string serial_number;
    result = sdk.getSerialNumber(serial_number);
    if (result == ErrorCode::SUCCESS) {
        std::cout << "🏷️  设备序列号: " << serial_number << std::endl;
    } else {
        std::cout << "⚠️  序列号读取失败 (错误码: " << static_cast<int>(result) << ")" << std::endl;
    }
    
    // 显示通信协议信息
    std::cout << "📡 通信协议: CAN-FD 1Mbps" << std::endl;
    std::cout << "🆔 命令ID: 0x64 | 数据ID: 0x65" << std::endl;
    
    // 读取固件编译时间
    std::string build_time;
    result = sdk.getFirmwareBuildTime(build_time);
    if (result == ErrorCode::SUCCESS) {
        std::cout << "📅 固件编译时间: " << build_time << std::endl;
    } else {
        std::cout << "⚠️  编译时间读取失败" << std::endl;
    }
}

/**
 * @brief 监听0x65 FT数据包
 */
void listenFTData(SixAxisSensorCANSDK& sdk) {
    std::cout << "\n📡 监听0x65 FT数据包..." << std::endl;
    std::cout << "💡 等待传感器自动上传数据，按 Ctrl+C 停止" << std::endl;
    std::cout << std::string(80, '-') << std::endl;
    
    // 等待2秒后再开始打印数据
    std::cout << "⏳ 等待2秒后开始显示数据..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "🔍 开始显示力值数据:" << std::endl;
    
    // 设置CAN帧监听回调
    sdk.setCANFrameCallback([&](const CANFrame& frame) {
        if (frame.id == sdk.getDataID()) {  // 使用动态数据ID
            ForceData data;
            if (sdk.parseFTData(frame, data) == ErrorCode::SUCCESS) {
                onDataReceived(data);
            }
        }
    });
    
    // 启动CAN消息监听
    ErrorCode result = sdk.startCANListener();
    if (result == ErrorCode::SUCCESS) {
        while (g_running.load()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        sdk.stopCANListener();
        std::cout << "\n🛑 数据监听已停止" << std::endl;
    } else {
        std::cerr << "❌ 启动CAN监听失败" << std::endl;
    }
}

int main(int argc, char* argv[]) {
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);
    
    std::cout << "🚀 六维力传感器CAN SDK示例程序" << std::endl;
    std::cout << "📦 SDK版本: " << SixAxisSensorCANSDK::getSDKVersion() << std::endl;
    
    // 创建SDK实例
    SixAxisSensorCANSDK sdk;
    g_sdk = &sdk;
    
    // 关闭调试模式
    sdk.setDebugMode(false);
    sdk.setErrorCallback([](ErrorCode error, const std::string& message) {
        std::cerr << "❌ 错误 [" << static_cast<int>(error) << "]: " << message << std::endl;
    });
    
    // 选择或指定CAN接口
    std::string interface_name;
    if (argc > 1) {
        interface_name = argv[1];
        std::cout << "📡 使用指定CAN接口: " << interface_name << std::endl;
    } else {
        interface_name = selectCANInterface(sdk);
        if (interface_name.empty()) {
            return -1;
        }
    }
    
    // 初始化CAN接口 - 使用固定波特率
    std::cout << "\n🔧 初始化CAN接口..." << std::endl;
    ErrorCode result = sdk.initCAN(interface_name, 1000000, 1000000, true);
    if (result != ErrorCode::SUCCESS) {
        std::cerr << "❌ CAN初始化失败" << std::endl;
        return -1;
    }
    std::cout << "✅ CAN接口初始化成功" << std::endl;
    
    // 读取设备信息
    showDeviceInfo(sdk);
    
    // 设置去皮功能
    if (!selectTareMode(sdk)) {
        std::cout << "⚠️ 去皮设置出现问题，但继续运行..." << std::endl;
    }
    
    // 启动数据监听
    std::cout << "\n" << std::string(50, '=') << std::endl;
    std::cout << "🚀 启动0x65 FT数据包监听模式" << std::endl;
    
    try {
        listenFTData(sdk);
    } catch (const std::exception& e) {
        std::cerr << "💥 异常: " << e.what() << std::endl;
    }
    
    // 清理
    sdk.closeCAN();
    std::cout << "🔌 连接已断开" << std::endl;
    std::cout << "✅ 程序结束" << std::endl;
    
    return 0;
}